package com.bckj.freshnow.payment.pay.extension.wxpay;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.cola.extension.Extension;
import com.bckj.freshnow.payment.model.RefundRequest;
import com.bckj.freshnow.payment.model.RefundResponse;
import com.bckj.freshnow.payment.pay.PaymentException;
import com.bckj.freshnow.payment.pay.PaymentServiceManager;
import com.bckj.freshnow.payment.pay.extension.RefundExtPt;
import com.bckj.freshnow.payment.pay.wxpay.WxRefundPaymentService;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.Refund;
import lombok.RequiredArgsConstructor;

import java.math.BigDecimal;

@Extension
@RequiredArgsConstructor
public class WxpayRefundExtPt implements RefundExtPt {

    private final PaymentServiceManager paymentServiceManager;

    @Override
    public RefundResponse refund(RefundRequest request) {
        WxRefundPaymentService paymentService = (WxRefundPaymentService) paymentServiceManager.getPaymentService(request.getAppId(), request.getRefundMethod());
        RefundService refundService = (RefundService) paymentService.getService();
        CreateRequest wechatRequest = toWechatRequest(request);
        try {
            Refund wechatResponse = refundService.create(wechatRequest);
            return toRefundResponse(wechatResponse);
        } catch (Exception e) {
            throw new PaymentException("Wechat Refund Error:" + e.getMessage());
        }
    }

    private CreateRequest toWechatRequest(RefundRequest request) {
        CreateRequest createRequest = new CreateRequest();
        createRequest.setOutTradeNo(request.getOutTradeNo());
        createRequest.setOutRefundNo(request.getOutRefundNo());
        createRequest.setReason(request.getReason());
        createRequest.setNotifyUrl(request.getNotifyUrl());
        AmountReq amountReq = new AmountReq();
        amountReq.setRefund(NumberUtil.mul(request.getAmount(), new BigDecimal("100")).longValue());
        amountReq.setCurrency("CNY");
        amountReq.setTotal(0L);
        createRequest.setAmount(amountReq);
        return createRequest;
    }

    private RefundResponse toRefundResponse(Refund wechatResponse) {
        RefundResponse refundResponse = new RefundResponse();
        return refundResponse;
    }
}
